package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.bean.AddressBook;
import com.itheima.common.R;
import com.itheima.dao.AddressBookDao;
import com.itheima.service.AddressBookService;
import com.itheima.utils.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@Transactional
@Slf4j
@RequestMapping("/addressBook")
public class AddressBookController {


    @Autowired
    private AddressBookService addressBookService;

    /**
     * 新建地址
     *
     * @param addressBook
     * @return
     */
    @PostMapping
    public R addAddress(@RequestBody AddressBook addressBook) {
        System.out.println(addressBook);
        int insert = addressBookService.insert(addressBook);
        if (insert > 0)
            return R.success("新建地址成功！！！");
        else return R.error("新建地址失败！！！");

    }

    /**
     * 查询当前用户的所有地址
     *
     * @return
     */
    @GetMapping("/list")
    public R selectByUserId() {
        List<AddressBook> addressBooks = addressBookService.selectByUserId();
        return R.success(addressBooks);
    }

    /**
     * 获取默认地址
     *
     * @return
     */
    @GetMapping("/default")
    public R getDefaultAddress() {
        AddressBook aDefault = addressBookService.getDefault();
        return R.success(aDefault);
    }

    /**
     * 设置默认地址
     *
     * @param addressBook
     * @return
     */
    @PutMapping("/default")
    public R setDefault(@RequestBody AddressBook addressBook) {

        int i = addressBookService.setDefault(addressBook);
        if (i > 0)
            return R.success("设置默认地址成功！！！");
        else return R.error("设置默认地址失败！！！");
    }

    @PutMapping
    public R updateAddress(@RequestBody AddressBook addressBook) {

        int row = addressBookService.updateAddress(addressBook);
        if (row > 0) {
            return R.success("修改地址成功");
        }
        return R.error("修改地址失败");
    }

    @GetMapping("/{id}")
    public R get(@PathVariable Long id) {
        AddressBook byId = addressBookService.getById(id);
        if (byId != null) {
            return R.success(byId);
        }
        return R.error("没找到对象");
    }

    @DeleteMapping
    public R dele(Long ids) {

        int row = addressBookService.dele(ids);
        if (row > 0) {
            return R.success("删除成功");
        }
        return R.error("删除失败");
    }
}
